<?php
if (!defined("LEVEL") || !defined("OK")) { header("Location: /"); }
unset($text);
if (isset($url['u']) && !empty($url['u'])) { $user = input(strtolower($url['u'])); } else { $user = ''; }
if (isset($url['i']) && isnum($url['i']) && $url['i'] > 0) { $pid = (int)$url['i']; } else { $pid = 0; }	//kam atsakom
if (isset($url['d']) && isnum($url['d']) && $url['d'] > 0) { $did = (int)$url['d']; } else { $did = 0; }	//ka trinam
if (isset($url['p']) && isnum($url['p']) && $url['p'] > 0) { $p = (int)$url['p']; } else { $p = 0; }	//puslapiavimas
if (isset($url['a']) && isnum($url['a']) && $url['a'] >= 0) { $a = (int)$url['a']; } else { $a = 1; } //inbox arba outbox
if (isset($url['o']) && !empty($url['o']) && $url['o'] != null) { $order = input($url['o']); } else { $order = 'date'; }	//lygiavimas
if (isset($url['s']) && !empty($url['s']) && $url['s'] != null) { $s = input($url['s']); }	//paieska
switch ($order) {
	case "Kada:": {
		$order = "date";
		break;
	}
	case "Siunt%C4%97jas:": {
		$order = "from";
		break;
	}
	case "Tema:": {
		$order = "title";
		break;
	}
	default: {
		$order = "date";
		break;
	}
}
$limit = 30;
$uzeris = mysql_fetch_assoc(mysql_query1("SELECT `pm_viso`,`nick` FROM ".LENTELES_PRIESAGA."users WHERE nick='" . $_SESSION['username'] ."'"));
$pm_sk = kiek("private_msg","WHERE `to`=".escape($uzeris['nick']));
$date['m'] = 'Viso';
$date['d'] = $pm_sk;
// ################# Trinam zinute ###########################
if (isset($url['d']) && isnum($url['d']) && $url['d'] >= 0 && isset($_SESSION['username'])) {
	if ($url['d'] == 0) {
		mysql_query1("DELETE FROM `".LENTELES_PRIESAGA."private_msg` WHERE `to`=".escape($_SESSION['username']));
		header("Location: ?id,45;p,".$url['p']."");
	}
	elseif ((int)$url['d'] > 0) {
		mysql_query1("DELETE FROM `".LENTELES_PRIESAGA."private_msg` WHERE `to`=".escape($_SESSION['username'])." AND `id`=".escape((int)$url['d']));
		header("Location: ?id,45;p,".$url['p']."");
	}
}

// ################# Siunciam zinute ##########################
if (isset($_POST['action']) && $_POST['action'] == 'pm_send' && isset($_SESSION['username'])) {
	$from = $_SESSION['username'];
	$to = input($_POST['to']);
	if ($to == $_SESSION['username']) { $error = "Sau privačios žinutės siųsti negalima<br />"; }
	$title = input($_POST['title']);
	if (!isset($title)) { $title = "[Be Pavadinimo]"; }
	$msg = $_POST['msg'];
	$date = date("Y-m-d H:i:s");
	$sql = mysql_query1("SELECT nick,email FROM ".LENTELES_PRIESAGA."users WHERE nick=".escape($to)." LIMIT 1");
	if (mysql_num_rows($sql) == 0) { $error = "Vartotojas kurį įvedėte neegzistuoja"; }
	if (!isset($error)) {
		if (kiek("private_msg","WHERE `to`=".escape($to)."") < 100) {
			$result = mysql_query1("INSERT INTO `".LENTELES_PRIESAGA."private_msg` (`from`, `to`, `title`, `msg`, `read`, `date`) VALUES (" . escape($from) .", " . escape($to) .", " . escape($title) .", " . escape($msg) .", 'NO', '" . $date ."')");
			if (!$result) { $error = "Jūsų žinutė neišsiųsta"; }
			if ($result) {
				$error = "Jūsų žinutė išssiųsta vartotojui <b>".$to."</b>";
				msg("Laiškas išsiųstas",$error);
				redirect("?id,45","meta");
			}
		}
		else { 			
			$sql = mysql_fetch_assoc($sql); //$result = mysql_query1("INSERT INTO `private_msg` (`from`, `to`, `title`, `msg`, `read`, `date`) VALUES (" . escape($conf['Pavadinimas']) .", " . escape($to) .", " . escape("Jūsų pašto dėžutė pilna") .", " . escape("Jūsų pašto dėžutė užsipildė. Kiti svetainės lankytojai jums nebegali siųsti žinučių.") .", 'NO', '" . $date ."')");
			klaida("Klaida","Vartotojo <b>".$to."</b> dėžutė pilna. Parašykite jam elektroninį laišką adresu ".preg_replace("#([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)#i", "<a href=\"javascript:mailto:mail('\\1','\\2');\">\\1_(at)_\\2</a>", $sql['email'])."");
			redirect("?id,45","meta"); 
		}
	}
}
// ######### Paneles rodymas ir zinuciu isvedimas ######################
$text = "
<fieldset>
<legend>Laisva vieta</legend>
<table border=0>
	<tr>
		<td>
		Liko: <b>" . ($uzeris['pm_viso'] - $pm_sk) . "</b><br />
		Išnaudota <b>" . $pm_sk ."</b> iš <b>" . $uzeris['pm_viso'] ."</b><br />";
$pm_img = substr($pm_sk, 0, -1);
$pm_img = "<img src='images/pm/".(empty($pm_img)?'0':$pm_img).".gif'/>";
$text .= $pm_img ."
		</td>
	</tr>
	<tr>
		<td></td>
	</tr>
</table>
</fieldset>

<fieldset>
<legend>Privačių žinučių veiksmai</legend>
	<table width='100%'>
		<tr>
			<td>
				<div class=\"blokas\"><center><a href='?id,45;n,1'><img src=\"images/pm/new.png\" alt=\"nauja\" />Rašyti</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45'><img src=\"images/pm/inbox.png\" alt=\"inbox\" />Gautos</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45;a,0'><img src=\"images/pm/outbox.png\" alt=\"outbox\" />Išsiųstos</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45;d,0' onclick=\"return confirm('Ar tikrai ištrinti visas žinutes?')\"><img src=\"images/pm/delete_all.png\" alt=\"trinti\" />Trinti viską</a></center></div>
			</td>
		</tr>
	</table>
 </fieldset>";

// ##################### Perziureti zinute ######################
if (isset($url['v'])) {
	if(!empty($url['v']) && (int)$url['v'] > 0 && isnum($url['v'])) {
		$sql = mysql_fetch_assoc(mysql_query1("SELECT `msg`, `from`, `title` FROM `".LENTELES_PRIESAGA."private_msg` WHERE `to`=".escape($_SESSION['username'])." AND id=".escape($url['v']).""));
		if ($sql) {
			$text .= "
				<fieldset>
				<legend>Privačios žinutės tekstas:</legend>
				<table border='0' width='100%'>
					<tr>
						<td class=\"title\" align=\"left\">Nuo: " . $sql['from'] ." Tema: ".input($sql['title'])."</td>
					</tr>
					<tr>
						<td width=\"50%\"  class=\"sarasas\" style=\"background-color: #FFFFCC\"><div align=\"justify\"><p>" . bbcode($sql['msg']) ."</p></div></td>
					</tr>
				</table>
				<form name=\"replay_pm\" action='?id,45;n,1;u," . $sql['from'] .";i," . $url['v'] ."' method=\"post\">
					<input type=\"submit\" value=\"Atsakyti\"/> <input type=\"button\" value=\"Trinti\" onclick=\"location.href='".url("d,".$url['v']."")."'\"/>
				</form>
				</fieldset>
			";
			mysql_query1("UPDATE `".LENTELES_PRIESAGA."private_msg` SET `read`='YES' WHERE `id`=".escape($url['v'])." AND `to`=".escape($_SESSION['username'])."");
		}
	}
}

// ################### Siusti nauja zinute arba atsakyti i esancia ######################################
if (isset($url['n'])) {
	if (!empty($url['n']) && (int)$url['n']) {
		// ############### Jei nera paspaustas atsakyti mygtukas sukuriam paprasta forma #################
		//if ((int)$pid == 0) {
			//$sql1 = mysql_query1("SELECT `nick` FROM users WHERE `nick` <> ".escape($_SESSION['username'])." ORDER BY nick ASC");
			if (isset($error) && !empty($error)) { msg("Dėmesio!",$error); }
			if (isset($user) && (int)$pid > 0) {
				$sql = mysql_fetch_assoc(mysql_query1("SELECT * FROM `".LENTELES_PRIESAGA."private_msg` WHERE `from`=".escape($user)." AND `id`=".escape($pid).""));
			}
			$text .= "
				<fieldset>
				<legend>".((isset($user) && (int)$pid > 0)?"Atsakyti":"Siųsti")." privačia žinutę</legend>
				<form name=\"msg\" action=\"?id,45;\" method=\"post\">
					<table border=0 width=\"100%\">
					<tr>
						<td width=\"15%\" class=\"sarasas\">Gavėjas:</td>
						<td>
							<input type=\"text\" name=\"to\" value=\"".(isset($user) && $_SESSION['username'] != $user?strtolower($user):'')."\" />
						</td>
					</tr>
					<tr>
						<td class=\"sarasas\">Tema:</td>
						<td><input name=\"title\" type=\"text\" size=\"50\" value=\"".((isset($user) && (int)$pid > 0)?"Re: " . $sql['title']:"")."\" style=\"width:95%\"></td>
					</tr>
					<tr>
						<td valign='top' align='left' class=\"sarasas\">Žinutė:</td>
						<td><textarea name=\"msg\" rows=\"10\" cols=\"50\" wrap=\"on\" style=\"width:95%\">".((isset($user) && (int)$pid > 0)?"[quote=" . $user ."]" . input(trim(preg_replace(array("#\[quote=(http://)?(.*?)\](.*?)\[/quote]#si","[/quote]"),"",$sql['msg']))) ."[/quote]\n\n":"")."</textarea>
						<br />
						".bbk("msg")."
						<br />
						<input type=\"submit\" value=\"".((isset($user) && (int)$pid > 0)?"Atsakyti":"Siųsti")."\">
						<input type=\"hidden\" name=\"action\" value=\"pm_send\" />
					</td>
					</tr>
					</table>
				</form>
			</fieldset><script>addText('msg', '', '');</script>
			";
		//}
	}
	else { header("Location: ?"); }
}

lentele("Privačių žinučių valdymas",$text); unset($text);
//$title = "Privačių žinučių valdymas";

if (defined("LEVEL") && LEVEL > 0 && $a == 1 && !isset($s)) {
	include_once("priedai/class.php");
	$sql = mysql_query1("SELECT `id`, `read`, IF(`from` = '', 'Svečias',`from`) AS `Nuo`, INSERT(LEFT(`msg`,80),80,3,'...') AS `Žinutė`, IF(`title` = '', 'Be pavadinimo',INSERT(LEFT(`title`,80),80,3,'...')) AS `Pavadinimas`, `date` AS `Data` FROM `".LENTELES_PRIESAGA."private_msg` WHERE `to`=".escape($_SESSION['username'])." ORDER BY `".LENTELES_PRIESAGA."private_msg`.`$order` DESC LIMIT $p,$limit") or die(mysql_error());
	if (mysql_num_rows($sql) > 0) {
		$bla = new Table();
		$info = array();
		while($row = mysql_fetch_assoc($sql)) {
			if ($row['read'] == "NO") {
				$extra ="<img src='images/pm/pm_new.png' />";
			} else {
				$extra = "<img src='images/pm/pm_read.png' />";
			}
			$info[]=array(
			""=> $extra,
			"Tema:"=>"<a href='?id,45;v,".$row['id']."' style=\"display: block\">".input($row['Pavadinimas'])."</a></div>",
			"Siuntėjas:"=>"<a href='?id,47;m,51' style=\"display: block\" title=\"header=[".$row['Nuo']."] body=[<br/>Data: <b>".$row['Data']."</b><br/>Kada: <b>".kada($row['Data'])."</b><br/>Žinutė: <i>".nl2br(strip_tags(input(str_replace(array("[","]"),"",$row['Žinutė']))))."</i><br/>] fade=[on]\">".$row['Nuo']."</a>",
			"Kada:"=>kada($row['Data']),
			" "=>"<a href='?id,45;n,1;u," . $row['Nuo'] .";i,".$row['id']."'><img src='images/pm/replay.png' border=0 alt=\"Atsakyti\" title=\"Atsakyti\"/></a><a href='".url('d,'.$row['id'].'')."'><img src='images/pm/delete.png' border=0 alt=\"Trinti\" title=\"Trinti\"/></a>"
			);
		}
		//asort($info);
		lentele("Gautos žinutės",puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10));
		//$title = "Gautos žinutės";
		//$text .= puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10);
	}
	else { klaida("Klaida","Laiškų nėra"); }
}
if (defined("LEVEL") && LEVEL > 0 && $a == 0 && !isset($s)) {
	include_once("priedai/class.php");
	$sql = mysql_query1("SELECT `id`, `read`, IF(`to` = '', 'Svečias',`to`) AS `to`, INSERT(LEFT(`msg`,80),80,3,'...') AS `Žinutė`, IF(`title` = '', 'Be pavadinimo',INSERT(LEFT(`title`,80),80,3,'...')) AS `Pavadinimas`, `date` AS `Data` FROM `".LENTELES_PRIESAGA."private_msg` WHERE `from`=".escape($_SESSION['username'])." ORDER BY `".LENTELES_PRIESAGA."private_msg`.`$order` DESC LIMIT $p,$limit") or die(mysql_error());
	if (mysql_num_rows($sql) > 0) {
		$bla = new Table();
		$info = array();
		while($row = mysql_fetch_assoc($sql)) {
			if ($row['read'] == "NO") {
				$extra ="<img src='images/pm/pm_new.png' />";
			} else {
				$extra = "<img src='images/pm/pm_read.png' />";
			}
			$info[]=array(
			""=> $extra,
			"Tema:"=>"<a href='?id,45;v,".$row['id']."' style=\"display: block\">".input($row['Pavadinimas'])."</a>",
			"Gavėjas:"=>"<a href='?id,47;m,51' style=\"display: block\" title=\"header=[".$row['to']."] body=[<br/>Data: <b>".$row['Data']."</b><br/>Kada: <b>".kada($row['Data'])."</b><br/>Žinutė: <i>".nl2br(strip_tags(input(str_replace(array("[","]"),"",$row['Žinutė']))))."</i><br/>] fade=[on]\">".$row['to']."</a>",
			"Kada:"=>kada($row['Data'])
			);
		}
		asort($info);
		lentele("Išsiųstos žinutės",puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10),"Laiškų dėžutė");
		//$title = "Išsiųstos žinutės";
		//$text = puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10);
	}
	else { klaida("Klaida","Laiškų nėra"); }
}
elseif (isset($s)) { klaida("Klaida","Ši dalis dar nėra suprogramuota"); }
?>
